package com.kdtech.utils;

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.io.UnsupportedEncodingException;
import java.util.List;

public class FileUtils {
	
	/** 
     * 将字符串写入指定文件(当指定的父路径中文件夹不存在时，会最大限度去创建，以保证保存成功！) 
     * 
     * @param res            原字符串 
     * @param filePath 文件路径 
     * @return 成功标记 
     */ 
    public static boolean string2File(String res, String filePath, String encoding) { 
        boolean flag = true; 
        File distFile = new File(filePath); 
        if (!distFile.getParentFile().exists()) distFile.getParentFile().mkdirs(); 
        /*
        BufferedReader bufferedReader = null; 
        BufferedWriter bufferedWriter = null; 
        try { 
            /*
            bufferedReader = new BufferedReader(new StringReader(res)); 
            bufferedWriter = new BufferedWriter(new FileWriter(distFile)); 
            char buf[] = new char[DEFAULT_BUFFER_SIZE];         //字符缓冲区 
            int len; 
            while ((len = bufferedReader.read(buf)) != -1) { 
            	bufferedWriter.write(buf, 0, len); 
            } 
            bufferedWriter.flush(); 
            bufferedReader.close(); 
            bufferedWriter.close(); 
        } catch (IOException e) { 
            e.printStackTrace(); 
            flag = false; 
            return flag; 
        } finally { 
            if (bufferedReader != null) { 
                try { 
                	bufferedReader.close(); 
                } catch (IOException e) { 
                	e.printStackTrace(); 
                } 
            } 
        } 
        */
        BufferedWriter writer = null;
        try {
	        writer = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(distFile), encoding));  
	        writer.write(res);
	        writer.flush();
        } catch (IOException e) {
        	e.printStackTrace();
        } finally {
        	if(null != writer) {
        		try {
					writer.close();
				} catch (IOException e) {
					e.printStackTrace();
				}
        	}
        }
        return flag; 
    }
    
    /** 
     * 文本文件转换为指定编码的字符串 
     * 
     * @param file         文本文件 
     * @param encoding 编码类型 
     * @return 转换后的字符串 
     * @throws IOException 
     */ 
    public static String file2String(File file, String encoding) {
    	/*
        InputStreamReader reader = null; 
        StringWriter writer = new StringWriter(); 
        String result = "";
        try { 
            if (encoding == null || "".equals(encoding.trim())) { 
            	reader = new InputStreamReader(new FileInputStream(file), encoding); 
            } else { 
            	reader = new InputStreamReader(new FileInputStream(file)); 
            } 
            //将输入流写入输出流 
            char[] buffer = new char[DEFAULT_BUFFER_SIZE]; 
            int n = 0; 
            while (-1 != (n = reader.read(buffer))) { 
            	writer.write(buffer, 0, n); 
            }
        } catch (Exception e) { 
        	e.printStackTrace(); 
        } finally { 
        	if (reader != null) {
        		try { 
        			reader.close(); 
        		} catch (IOException e) { 
        			e.printStackTrace(); 
        		} 
        	}
        } 
        //返回转换结果 
        if (writer != null) {
        	result = writer.toString();
        	try {
				writer.close();
			} catch (IOException e) {
				e.printStackTrace();
			}
        }
        return result;
        */
    	
    	String result = "";  
        BufferedReader reader = null;
		try {
			reader = new BufferedReader(new InputStreamReader(new FileInputStream(file), encoding));
			String line = null;  
	        while ((line = reader.readLine()) != null) {  
	        	result += line;
	        }  
		} catch (UnsupportedEncodingException | FileNotFoundException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		} finally {
			if(null != reader) {
				try {
					reader.close();
				} catch (IOException e) {
					e.printStackTrace();
				}  
			}
		}
       
        return result;  
    }
    
    /** 
     * 复制单个文件(原名复制) 
     * @param oldPathFile 准备复制的文件源 
     * @param newPathFile 拷贝到新绝对路径带文件名(注：目录路径需带文件名) 
     * @return 
     */  
    public static boolean CopySingleFileTo(String srcPath, String destDir) {
    	String encoding = "UTF-8";
    	BufferedReader reader = null;
    	BufferedWriter writer = null;
        boolean success = false;
    	try {  
            File srcFile = new File(srcPath);  
            String targetfile = destDir + File.separator +  srcFile.getName();  
            if (srcFile.exists()) { //文件存在时  
            	reader = new BufferedReader(new InputStreamReader(new FileInputStream(srcFile), encoding));
            	writer = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(targetfile), encoding));
                String line = null;
                while ((line = reader.readLine()) != null) {  
                    writer.write(line);
                }
            }
            success = true;
        } catch (Exception e) {  
            e.printStackTrace();  
            success = false;
        }  finally {
        	if(null != reader) {
        		try {
					reader.close();
				} catch (IOException e) {
					e.printStackTrace();
				}
        	}
        	if(null != writer) {
        		try {
        			writer.flush();
        			writer.close();
				} catch (IOException e) {
					e.printStackTrace();
				}
        	}
        }
    	return success;
    } 
    
    public static void getAllFileNames(String dir, List<String> fileNames)
    {
      if ((dir == null) || ("".equals(dir))) {
        return;
      }
      File file = new File(dir);
      if (file.isFile())
      {
        fileNames.add(file.getPath());
      }
      else if (file.isDirectory())
      {
        File[] childFiles = file.listFiles();
        File[] arrayOfFile1;
        int j = (arrayOfFile1 = childFiles).length;
        for (int i = 0; i < j; i++)
        {
          File childFile = arrayOfFile1[i];
          if (childFile.isFile()) {
            fileNames.add(childFile.getPath());
          } else {
            getAllFileNames(childFile.getPath(), fileNames);
          }
        }
      }
    }
    
    public static void getChildrenDir(String dir, List<String> dirPaths)
    {
      if ((dir == null) || ("".equals(dir))) {
        return;
      }
      File file = new File(dir);
      if (file.isDirectory())
      {
        File[] children = file.listFiles();
        File[] arrayOfFile1;
        int j = (arrayOfFile1 = children).length;
        for (int i = 0; i < j; i++)
        {
          File child = arrayOfFile1[i];
          if (child.isDirectory()) {
            dirPaths.add(child.getPath());
          }
        }
      }
    }
    
    public static boolean hasNormalFiles(String dir)
    {
      if ((dir == null) || ("".equals(dir))) {
        throw new RuntimeException("the directory is null or empty!");
      }
      File file = new File(dir);
      if (file.isDirectory())
      {
        File[] children = file.listFiles();
        if (children.length == 0) {
          return false;
        }
        return true;
      }
      throw new RuntimeException("the direcotry is not a real directory!");
    }
    
    public static void delete(String filePath)
    {
      if ((filePath == null) || ("".equals(filePath))) {
        return;
      }
      File file = new File(filePath);
      if (file.isFile()) {
        file.delete();
      }
    }
    
    public static void main(String[] args) {
//      List<String> list = new ArrayList();
//      getChildrenDir("D:\\logs", list);
//      for (String file : list) {
//        System.out.println(file);
//      }
    	String srcPath = "test/test.txt";
    	String destDir = "test-backup";
    	System.out.println(CopySingleFileTo(srcPath, destDir));
    }
}
